#include "Server.hpp"
#include <memory>
#include "onlineServer.hpp"
using namespace onlineServer;

void Usage(const string msg)
{
     cout << "\nUsage:\n\t" << msg << " local_port\n\n";
}

onlineUser g_onlineuser;

//回调处理函数，负责统计在线用户并进行消息路由
void routeMessage(int sock,std::string clientip,uint16_t clientport,std::string message)
{
    if(message=="online") g_onlineuser.addUser(clientip,clientport,sock);
    if(message=="offline") g_onlineuser.delUser(clientip,clientport);
    if(g_onlineuser.isOnline(clientip,clientport))
    {
        //消息的路由
        g_onlineuser.messageRouting(clientip,clientport,message);
    }
    else
    {
        //发送信息
        string response=clientip+"["+std::to_string(clientport)+"]请先上线再说话！！！，键盘输入online";
        send(sock,response.c_str(),response.size(),0);
    }
}

int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    
    uint16_t port=atoi(argv[1]);
    unique_ptr<Server> svr(new Server(routeMessage,port));
    svr->init();
    svr->run();
    return 0;
}